package com.vf.cloud.rendering.common.datasource.config;

import java.net.URL;
import java.net.URLDecoder;
import java.sql.Connection;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.vf.cloud.rendering.common.mapping._MappingKit;

@Primary
@Configuration
public class ActiveRecordPluginConfig implements InitializingBean, DisposableBean {

	DruidPlugin druidPlugin;
	ActiveRecordPlugin arp;

	public void destroy() throws Exception {

		druidPlugin.stop();
		arp.stop();
	}

	public void afterPropertiesSet() throws Exception {
		String path = String.format("%sresources/db/server.db", getPath());
		druidPlugin = new DruidPlugin("jdbc:sqlite:E:\\code\\sts\\workspace-micros\\VFCloud-Rendering\\src\\main\\resources\\db\\server.db" , "", "");
		//druidPlugin = new DruidPlugin("jdbc:sqlite:" + path, "", "");
		druidPlugin.set(5, 5, 50);
		druidPlugin.setDriverClass("org.sqlite.JDBC");
		druidPlugin.setLogAbandoned(true);
		druidPlugin.setTestWhileIdle(true);
		druidPlugin.setRemoveAbandoned(true);
		
		arp = new ActiveRecordPlugin("sqlite", druidPlugin);
		arp.setShowSql(false);
		arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
		arp.getEngine().setToClassPathSourceFactory();
		arp.setDialect(new Sqlite3Dialect());
		
		_MappingKit.mapping(arp);
		
		druidPlugin.start();
		arp.start();
	}

	public String getPath() {
		URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
		String filePath = null;
		try {
			filePath = URLDecoder.decode(url.getPath(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		filePath = filePath.substring(1, filePath.lastIndexOf("/") + 1);
		return filePath;
	}

}
